package com.greenbook.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.greenbook.entity.UserAuth;
import com.greenbook.mapper.UserAuthMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义UserDetailsService实现
 * 用于加载用户信息并转换为Spring Security所需的UserDetails对象
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserAuthMapper userAuthMapper;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        // 查询用户信息
        UserAuth userAuth = userAuthMapper.selectById(Long.parseLong(userId));
        if (userAuth == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }

        // 创建UserDetails对象
        return new User(
                String.valueOf(userAuth.getId()),                     // 用户ID
                userAuth.getPassword(),                               // 密码
                userAuth.getStatus() == 1,                            // 账户是否启用
                userAuth.getDeleted() == 0,                           // 账户是否未过期
                userAuth.getDeleted() == 0,                           // 凭证（密码）是否未过期
                userAuth.getStatus() == 1,                            // 账户是否未锁定
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))  // 权限列表
        );
    }
}